import 'package:flutter/cupertino.dart';
import 'package:flutter_09_game/base/controller/base_list_controller.dart';
import 'package:flutter_09_game/base/controller/base_list_more_controller.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/config/history_route_ovserver.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/pages/home/models/model_home_pool.dart';
import 'package:flutter_09_game/pages/profile/profile_bet_record/models/model_bet_battle_list.dart';
import 'package:flutter_09_game/pages/profile/profile_bet_record/models/model_third_game_list.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/user/model/model_user_wallet.dart';
import 'package:flutter_09_game/utils/extensions/num_ext.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/shared/shared_export.dart';
import 'package:flutter_09_game/utils/shared/shared_storage.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/widgets/dialog/notice_popup_dialog.dart';
import 'package:flutter_09_game/widgets/dialog/widget_dialog_package.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher_string.dart';
import '../../../http/http_export.dart';
import 'models/model_home_banner.dart';
import 'models/model_home_game.dart';
import 'models/model_notice_active.dart';

class HomeLogic extends BaseListMoreController {
  // 奖池数据
  final Rx<ModelHomePool> prizePoolRx = ModelHomePool().obs;

  // Banner数据
  final RxList<ModelHomeBanner> bannerList = <ModelHomeBanner>[].obs;

  // 游戏标签数据
  final RxList<ModelHomeGame> gameTagList = <ModelHomeGame>[].obs;

  // 当前选中的游戏标签ID
  final RxInt selectedGameTagId = 1.obs;

  // 当前选中标签的游戏列表
  final RxList currentGameList = [].obs;

  final RxInt selectBannerRx = 0.obs;

  // 公告数据
  final RxList<ModelNoticeActive> noticeList = <ModelNoticeActive>[].obs;

  // bool isGetNotice = false;

  RxInt poolCountRx = 0.obs;
  bool isFirst = true;

  // 骨架图显示状态
  RxBool isShowingSkeleton = true.obs;

  @override
  // TODO: implement pageSize
  int get pageSize => 9;

  @override
  // TODO: implement canLoadMore
  bool get canLoadMore {
    // clog('canLoadMore ${currentGameList.length}   $pageSize ');
    // return currentGameList.length ~/ 9 <= pageSize;
    return true;
  }

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    // 页面准备就绪时的操作
    _startPrizePoolUpdates();
  }

  @override
  void onClose() {
    super.onClose();
    // 页面关闭时的清理操作
  }

  @override
  Future<List> loadData() async {
    if (pageNum == 1) {
      if (isFirst && AppUserManager().token.isNotEmpty) {
        isFirst = false;
        UtilsOther().getAppPackage();
        // Future.delayed(const Duration(seconds: 2)).then((v) {
        //   isShowingSkeleton.value = false;
        // });
      }
      _loadBannerData();
      _loadPoolData();
      loadNoticeData();

      _loadHomeRewardTimes();
      _loadGameTagData().then((value) async {
        await Future.wait([
          getThirdGameList(0),
          getThirdGameList(1),
        ]);
        update();
      });
    } else {
      getThirdGameList(0);
    }

    // AppUserManager().loadWalletData();
    return [1];
  }

  /// 开始奖池数据更新
  void _startPrizePoolUpdates() {
    // TODO: 实现定时更新奖池数据
    // 可以使用Timer.periodic来定期更新数据
  }

  // /// 更新奖池数据
  // void updatePrizePoolData(PrizePoolData newData) {
  //   prizePoolData.value = newData;
  // }

  /// 加载pool数据
  Future<void> _loadPoolData() async {
    HttpResponse response = await HttpManager().get(
      API.getHomePrizePool,
      fromJson: ModelHomePool.fromJson,
      uiType: HttpUIType.none, // 静默加载，不显示loading
    );

    if (response.isSuccess) {
      prizePoolRx.value = ModelHomePool();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        prizePoolRx.value = response.data;
      });
    }
  }

  beginPoolAnimated() {
    ModelHomePool homePool = prizePoolRx.value;
    prizePoolRx.value = ModelHomePool();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      prizePoolRx.value = homePool;
    });
  }

  /// 加载公告数据
  Future<void> loadNoticeData() async {
    if (AppUserManager().isLogin()) {
      HttpResponse response = await HttpManager().get(
        API.getNoticeActive,
        fromJson: ModelNoticeActive.fromJson,
        uiType: HttpUIType.none, // 静默加载，不显示loading
      );

      if (response.isSuccess) {
        noticeList.value = response.data ?? [];
        // 如果有公告数据，显示弹窗
        if (noticeList.isNotEmpty &&
            !routeHistoryObserver.history
                .map((router) => router.settings.name ?? '')
                .contains(NoticePopupDialog.name) &&
            !routeHistoryObserver.history
                .map((router) => router.settings.name ?? '')
                .contains(WidgetDialogPackage.name)) {
          // WidgetDialogPackage
          NoticePopupDialog.show(noticeList);
        }
      }
    }
  }

  _loadHomeRewardTimes() async {
    HttpResponse response = await HttpManager().get(
      API.getHomeRewardTimes,
      uiType: HttpUIType.none, // 静默加载，不显示loading
    );

    if (response.isSuccess) {
      poolCountRx.value = response.data ?? 0;
    }
  }

  /// 检查是否应该显示公告弹窗
  // bool _shouldShowNoticePopup() {
  //   final noShowUntil =
  //       SharedStorage().prefs.getInt(SharedKey.noticeNoShowUntil);
  //   if (noShowUntil != null) {
  //     final expireTime = DateTime.fromMillisecondsSinceEpoch(noShowUntil);
  //     final now = DateTime.now();
  //     if (now.isBefore(expireTime)) {
  //       return false; // 还在24小时内，不显示
  //     } else {
  //       // 超过24小时，清除存储状态
  //       SharedStorage().prefs.remove(SharedKey.noticeNoShowUntil);
  //     }
  //   }
  //   return true; // 可以显示
  // }

  /// 加载Banner数据
  Future<void> _loadBannerData() async {
    HttpResponse response = await HttpManager().get(
      API.getBannerActive,
      fromJson: ModelHomeBanner.fromJson,
      uiType: HttpUIType.none, // 静默加载，不显示loading
    );

    if (response.isSuccess) {
      bannerList.value = response.data ?? [];
    }
  }

  /// 刷新Banner数据
  Future<void> refreshBannerData() async {
    await _loadBannerData();
  }

  /// 处理Banner点击
  void handleBannerTap(ModelHomeBanner banner) {
    if (!AppUserManager().isLogin()) {
      Get.toNamed(AppRoutes.loginPage);
      return;
    }
    if (banner.linkUrl != null && banner.linkUrl!.isNotEmpty) {
      if (banner.linkUrl?.startsWith('http') == true) {
        launchUrlString(banner.linkUrl ?? "",
            mode: LaunchMode.externalApplication);
      } else {
        Get.toNamed(AppRoutes.webPage, arguments: {
          'url':
              "${AppConfig.shareUrl}/${banner.linkUrl}${banner.linkUrl?.contains('?') == true ? '&' : '?'}token=${AppUserManager().token}",
          'isGame': false
        })?.then((v) {
          loadNoticeData();
        });
      }
    }
  }

  /// 加载游戏标签数据
  Future<void> _loadGameTagData() async {
    HttpResponse response = await HttpManager().get(
      API.getTagActive,
      fromJson: ModelHomeGame.fromJson,
      uiType: HttpUIType.none, // 静默加载，不显示loading
    );

    if (response.isSuccess) {
      gameTagList.value = response.data ?? [];
      // 如果有数据，默认选中第一个标签并更新游戏列表
      for (var item in gameTagList) {
        if ((item.room ?? []).isNotEmpty) {
          item.game ??= [];
          if (item.id == 2) {
            item.game?.insertAll(0, item.room ?? []);
          } else {
            item.game?.addAll(item.room ?? []);
          }
        }
      }
      if (gameTagList.isNotEmpty) {
        selectedGameTagId.value = gameTagList.first.id ?? 1;
        _updateCurrentGameList();
      }
    }
  }

  /// 刷新游戏标签数据
  Future<void> refreshGameTagData() async {
    await _loadGameTagData();
  }

  /// 切换游戏标签
  void switchGameTag(int tagId) {
    if (selectedGameTagId.value != tagId) {
      selectedGameTagId.value = tagId;
      _updateCurrentGameList();
    }
  }

  /// 更新当前选中标签的游戏列表
  void _updateCurrentGameList() {
    final selectedTag = gameTagList.firstWhereOrNull(
      (tag) => tag.id == selectedGameTagId.value,
    );

    if (selectedTag != null && selectedTag.game != null) {
      currentGameList.value = selectedTag.game!;
    } else {
      currentGameList.clear();
    }
    update();
  }

  Future getThirdGameList(int type) async {
    // List<ModelBetBattleList> bets = [];

    // HttpResponse response1 = await HttpManager().get(API.getBattleRoyaleList,
    //     // page=3&size=9&type=0
    //     params: {'page': pageNum, 'size': pageSize, 'type': type},
    //     fromJson: ModelBetBattleList.fromJson);
    // if (response1.isSuccess) {
    //   bets = response1.data;
    // }

    HttpResponse response = await HttpManager().get(
      API.getThirdGameList,
      params: {'page': pageNum, 'size': pageSize, 'type': type},
    );
    if (response.isSuccess) {
      List<ModelThirdGameList> games = List<ModelThirdGameList>.from(
          (response.data['list'] as List)
              .map((e) => ModelThirdGameList.fromJson(e)));

      if (type == 1) {
        ModelHomeGame? homeGame =
            gameTagList.firstWhereOrNull((item) => item.id == 1);
        if (homeGame != null) {
          // homeGame.game?.addAll(bets);
          homeGame.game?.addAll(games);
        }
      } else if (type == 0) {
        ModelHomeGame? homeGame =
            gameTagList.firstWhereOrNull((item) => item.id == 4);
        if (homeGame != null) {
          // homeGame.game?.addAll(bets);
          homeGame.game?.addAll(games);
        }
        // ModelHomeGame? homeGame1 =
        // gameTagList.firstWhereOrNull((item) => item.id == 2);
        // if (homeGame1 != null) {
        //   homeGame1.game?.insertAll(0,bets);
        //   // homeGame.game?.addAll(games);
        // }
      }
      update();
    }
  }

  /// 处理游戏项点击
  void handleGameItemTap(dynamic gameItem) async {
    if (!AppUserManager().isLogin()) {
      Get.toNamed(AppRoutes.loginPage);
      return;
    }
    // notDevelopedYet

    if (gameItem is ModelThirdGameList) {
      if (gameItem.status == 2) {
        LoadingUtils.showToast(LocaleKeys.notOpenYet.tr);
        return;
      }
      HttpResponse response = await HttpManager().post(
        API.postStartThirdGame,
        params: {
          'gameCode': gameItem.gameCode,
          'vendorCode': gameItem.vendorCode,
        },
      );
      if (response.isSuccess) {
        Get.toNamed(AppRoutes.webPage,
            arguments: {'url': response.data, 'isGame': true})?.then((v) {
          loadNoticeData();
        });
      }
    } else if (gameItem is ModelBetBattleList) {
      if (gameItem.status == 2) {
        LoadingUtils.showToast(LocaleKeys.notOpenYet.tr);
        return;
      }
      HttpResponse response = await HttpManager().get(
        API.getStartBetsGame,
        params: {
          'room_id': gameItem.id,
          // 'vendorCode': gameItem.vendorCode,
        },
      );
      if (response.isSuccess) {
        Get.toNamed(AppRoutes.webPage,
                arguments: {'url': response.data['url'], 'isBet': true,'isGame': true})
            ?.then((v) {
          loadNoticeData();
        });
      }
    } else {
      if (gameItem.status == 2) {
        LoadingUtils.showToast(LocaleKeys.notOpenYet.tr);
        return;
      }
      Get.toNamed(AppRoutes.gameDetailPage,
          arguments: {'id': gameItem.id, 'name': gameItem.name})?.then((v) {
        loadNoticeData();
      });
    }
  }
}
